<script setup lang="ts">
import { reactive, useSlots, watch } from "vue";

defineOptions({ name: "WebxInputModal" });
const emits = defineEmits(["update:value"]);
const props = defineProps({
  // 输入框内容
  value: { type: String, default: "" },
  // 弹窗属性
  modalProps:{ type: Object, default: () => ({}) }
});
const slots = useSlots();
// 绑定真实值
const inputModalData = reactive({
  value:props.value
});
// 弹框数据
const modalData = reactive({
  open:false,
  change(open:boolean){
    modalData.open = open;
  }
})

watch(() => inputModalData.value, () => {
  emits("update:value", inputModalData.value);
})
watch(() => props.value, () => {
  inputModalData.value = props.value;
})

// 获取输入框需要的插槽
function getInputSlots(){
  return Object.entries(slots)
    .filter(([slotName, slotFn]) => slotName !== "modal")
    .reduce((acc, [slotName, slotFn]) => {
      acc[slotName] = slotFn;
      return acc;
    },{} as Record<string, any>)
}
// 关闭弹窗
function closeModal(){
  modalData.change(false);
}
</script>

<template>
  <div>
    <AInput v-model:value="inputModalData.value" v-bind="$attrs" readonly @click="modalData.change(true)">
      <!-- 透传所有插槽 -->
      <template v-for="(_, slotName) in getInputSlots()" #[slotName]="slotData">
        <slot :name="slotName" v-bind="slotData || {}" />
      </template>
    </AInput>
    <!-- 弹窗 -->
    <AModal v-model:open="modalData.open" v-bind="modalProps" destroyOnClose>
      <AFormItemRest>
        <slot name="modal" v-bind="{ closeModal }" />
      </AFormItemRest>
    </AModal>
  </div>
</template>

<style scoped lang="less"></style>
